<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Bull_mdl extends CI_Model {

  const TABLE = 'bull';

	public function select(){
        return $this->db->get(self::TABLE)->result_array();
    }

    public function get_one(){
        return $this->db->get(self::TABLE)->row_array();
    }

    //统计
    public function get_count(){
        return $this->db->count_all_results(self::TABLE);
    }

    //统计金额
    public function get_sum(){
      $this->db->select_sum('bull');
      return $this->db->get(self::TABLE)->row_array();
    }

    //添加
    public function create($data){
        return $this->db->insert(self::TABLE,$data);
    }
    //修改
    public function update($data){
        return $this->db->update(self::TABLE,$data);
    }
    //删除
    public function delete(){
        return $this->db->delete(self::TABLE);
    }

    //数据组装
    public function assembly($list){
      $this->load->model('users_mdl');
      $this->load->model('level_mdl');
      $this->load->model('shops_mdl');

      //查询当前商铺金额
      $this->db->where('shops_id',$list[0]['shops_id']);
      $res_shops = $this->shops_mdl->get_one();


      foreach($list as $k => $v){
        //用户详情
        if(!empty($v['uid'])){
          $this->db->where('user_id',$v['uid']);
          $list[$k]['user'] = $this->users_mdl->get_one();
        }

        //权限等级
        if(!empty($v['level_id'])){
          if($v['level_id'] == -1){
            $list[$k]['percentage'] = '--';
            $list[$k]['level_name'] = '系统收入';
          }else{
            $this->db->where('id',$v['level_id']);
            $this->db->select('name');
            $res = $this->level_mdl->get_one();
            $list[$k]['level_name'] = $res['name'];
            $list[$k]['percentage'] = $v['bull'] / $res_shops['income'] * 100;
          }
        }

        //查询商铺
        if(!empty($v['shops_id'])){
          $this->db->where('shops_id',$v['shops_id']);
          $this->db->select('name,income,end_time');
          $list[$k]['shops'] = $this->shops_mdl->get_one();
          $list[$k]['percentage'] = $v['bull'] / $list[$k]['shops']['income'] * 100;
        }

      }

      return $list;
    }

    /**
     * 资金分配（核心）
     * @param  int $user_id  用户id
     * @param  int $shops_id 商铺ID
     */
    public function distribution($sid,$static = ''){
    	if(empty($sid)){
    		die('参数错误！');
    	}
      //获取该商铺所入金额
      $this->load->model('shops_mdl');
      $this->db->where('id',$sid);
      $shops = $this->shops_mdl->get_one();

    	//获取当前整条线上的用户
   		$this->load->model('users_mdl');
   		$list_user = $this->users_mdl->get_superior($shops['uid']);

   		//获取当前所有权限层级
   		$this->load->model('level_mdl');
   		$this->db->order_by('hierarchy desc');
   		$list_level = $this->level_mdl->select();

   		//叠加百分比
   		$percentage = 0;
   		//总共支出
   		$sum = 0;
   		//邮件发送统计
   		$email_arr = array();

   		foreach($list_level as $k => $v){

   			$percentage += $v['commission'];

   			if($v['hierarchy'] == 0){
   				//必算
   				$data = [
   					'uid' => 0,
   					'level_id' => $v['id'],
   					'shops_id' => $shops['shops_id'],
   					'bull' => $shops['income'] * $v['commission'],
   					's_time' => $_SERVER['REQUEST_TIME']
   				];
   				$email_arr[] = [
   					'name' => '支付提成+税收',
   					'level' => $v['name'],
   					'bili' => $v['commission']*100,
   					'bull' => $data['bull']
   				];
   				$this->create($data);
   				$sum += $data['bull'];
   				continue;
   			}

   			foreach($list_user as $key => $value){

   				if($value['level_id'] == 0){
   					continue;
   				}

   				if($value['level_id'] == $v['group_id']){
		            if($percentage > $v['max']){
		              $percentage = $v['max'];
		            }

   					$data = [
	   					'uid' => $value['user_id'],
	   					'level_id' => $v['id'],
	   					'shops_id' => $shops['shops_id'],
	   					'bull' => $shops['income'] * $percentage,
	   					's_time' => $_SERVER['REQUEST_TIME']
	   				];

	   				$email_arr[] = [
	   					'name' => $value['user_name'].'##'.$value['username'],
	   					'level' => $v['name'],
	   					'bili' => $percentage*100,
	   					'bull' => $data['bull']
	   				];
	   				$this->create($data);
	   				$percentage = 0;
	   				$sum += $data['bull'];
		   			continue;	
   				}
   			}
   		}

   		$data = [
  			'uid' => '-1',
  			'level_id' => '-1',
  			'shops_id' => $shops['shops_id'],
  			'bull' => $shops['income'] - $sum,
  			's_time' => $_SERVER['REQUEST_TIME']
  		];

  		$email_arr[] = [
			'name' => '系统收入',
			'level' => '系统收入',
			'bili' => '--',
			'bull' => $data['bull']
		];
  		$this->create($data);

  		//邮件提醒
  		$str = "##商铺订单入账提醒： \n\n";

      if($static == 'update'){
        $str .= '-------商铺数据更新-------'." \n\n";
      }

  		$str .= '商铺:'.$shops['name']." \n";
      $str .= '金额:'.$shops['income']." \n\n";
  		foreach($email_arr as $k => $v){
  			$str .= "-----------------   \n";
  			$str .= '名称： ' .$v['name']." \n";
  			$str .= '权限： ' .$v['level']." \n";
  			$str .= '提成比： ' .$v['bili']."% \n";
  			$str .= '金额： ' .$v['bull']." \n\n";
  		}

      $str .= "此信件请勿回复，感谢！##";
  		
  		$this->send_admin($str);

		return true;

    }

    /** 邮件通知（通知管理员） */
    private function send_admin($content){
        $this->load->library('email');

        //设置发信人email地址和名称
        $this->email->from('zbzmall@yeah.net', $this->system->title, 'dickfan@yeah.net');
        //设置邮件回复地址
        $this->email->reply_to($this->system->email, $this->system->title);
        //设置发送地址
        $this->email->to($this->system->email);

        $this->email->subject($this->system->title.'-账单提醒');//主题
        $this->email->message($content); //内容

        $this->email->send();
    }

}

/* End of file Bull_mdl.php */
/* Location: ./application/models/Bull_mdl.php */